package controllers

// 控制层所有公开的接口函数必须验证用户身份

import (
	"net/http"

	"bsm/logger"
	"bsm/models"
	"bsm/services"

	"github.com/gin-gonic/gin"
)

type PmsController interface {
	GetOrgAll(ctx *gin.Context)
	GetProjectDiff(ctx *gin.Context)
	GetProjectDiffDetail(ctx *gin.Context)
}

type pmsControllerImpl struct {
	svcQuery services.CompareService
	svcAuth  services.AuthService
}

func NewPmsController(querySvc services.CompareService, authSvc services.AuthService) PmsController {
	return &pmsControllerImpl{
		svcQuery: querySvc,
		svcAuth:  authSvc,
	}
}

// 获取建设单位
func (c *pmsControllerImpl) GetOrgAll(ctx *gin.Context) {
	// 验证用户信息
	if !c.svcAuth.JWTAuthUser(ctx) {
		return
	}

	data, err := c.svcQuery.GetOrgAll()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "Pms-GetOrgAll",
		}).Errorf("获取建设单位失败: %v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"信息": "获取建设单位失败"})
		return
	}
	ctx.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: len(data), // 总记录数
		Data:  data,
	})
}

func (c *pmsControllerImpl) GetProjectDiff(ctx *gin.Context) {
	// 验证用户信息
	if !c.svcAuth.JWTAuthUser(ctx) {
		return
	}

	prjname := ctx.Query("projectName")
	data, err := c.svcQuery.GetProjectDiff(prjname)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "Pms-GetProjectDiff",
		}).Errorf("获取项目差异失败: %v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"信息": "获取项目差异失败"})
		return
	}
	ctx.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: len(data), // 总记录数
		Data:  data,
	})
}
func (c *pmsControllerImpl) GetProjectDiffDetail(ctx *gin.Context) {
	// 验证用户信息
	if !c.svcAuth.JWTAuthUser(ctx) {
		return
	}

	pcode := ctx.Query("project_code")
	data, err := c.svcQuery.GetProjectDiffDetail(pcode)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "Pms-GetProjectDiffDetail",
		}).Errorf("获取项目差异详情失败: %v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{"信息": "获取项目差异详情失败"})
		return
	}
	ctx.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: len(data), // 总记录数
		Data:  data,
	})
}
